package com.culturalCenter.dataCenter.globalconfig.filter;


import com.culturalCenter.dataCenter.Utils.ApiResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 异常处理_登录后的无权访问
 *
 * @author Mr.WU
 */
@Component
@Slf4j
public class AccessDenied implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
        log.error("当前用户没有访问该资源的权限：{}", e.getMessage());
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        httpServletResponse.setStatus(200);
        ObjectMapper om = new ObjectMapper();
        out.write(om.writeValueAsString(ApiResult.instance("403", e.getMessage())));
        out.flush();
        out.close();
    }

}
